<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="root">
        <ul>
            <li>
                <a href="">
                    <img src="" alt="">
                </a>
            </li>
            <li>
                <span></span>
            </li>
            <li>
            </li>
        </ul>
        <p></p>
        <button></button>
    </div>
    <script>
        // 1-1方法一：递归方式
        // function deepFirstSearch(node, nodeList) {
        //     if (node) {
        //         nodeList.push(node);
        //         var children = node.children;
        //         for (var i = 0; i < children.length; i++)
        //             //每次递归的时候将 需要遍历的节点 和 节点所存储的数组nodeList传下去
        //             deepFirstSearch(children[i], nodeList);
        //     }
        //     return nodeList;
        // }
        // let root = document.getElementById('root')
        // var nodeList = deepFirstSearch(root, [])
        // console.log(nodeList);
        // 1-2方法二：非递归方式
        function deepFirstSearch(node) {
            var nodeList = [];
            if (node != null) {
                var stack = [];
                stack.push(node);
                while (stack.length != 0) {
                    var item = stack.pop(); // 出栈，先弹出左边的子节点
                    nodeList.push(item);
                    var children = item.children;
                    for (var i = children.length - 1; i >= 0; i--)
                        // 入栈顺序为：子节点从右向左入栈
                        stack.push(children[i]);
                }
            }
            /* 将最终遍历结果存放在nodeList数组中。*/
            return nodeList;
        }
        let root = document.getElementById('root')
        var nodeList = deepFirstSearch(root)
        console.log(nodeList);
    </script>
</body>

</html>